package com.chengh.nami.common.response;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;
import org.springframework.util.CollectionUtils;

import java.io.Serializable;
import java.util.List;

/**
 * @author chengh
 * 通用的分页返回类
 */
@Getter
@Setter
@ToString
public class PageData<T> implements Serializable {
    private static final long serialVersionUID = 1L;

    private PageResult pageResult;

    private List<T> records;

    public static <T> PageData<T> build(Page<T> page) {
        PageData<T> pageData = new PageData<>();
        PageResult pageResultInfo = PageResult.builder().pageTotal(page.getPages()).totalRecords(page.getTotal()).pageNum(page.getCurrent()).pageSize(page.getSize()).build();
        pageData.setPageResult(pageResultInfo);
        pageData.setRecords(page.getRecords());
        return pageData;
    }

    public static <T> PageData<T> build(List<T> list) {
        PageData<T> pageData = new PageData<>();
        PageResult result = PageResult.builder().totalRecords(CollectionUtils.isEmpty(list) ? 0L : (long) list.size()).build();
        pageData.setPageResult(result);
        pageData.setRecords(list);
        return pageData;
    }

}
